/**
 * @Description: 利用html2canvas控制拖拽dom
 * @author Beon
 * @date 2021/6/29
*/
import * as html2canvas from 'html2canvas';
import DomCreate from './domCreate';
import ToolsDec from '../decorators/toolsDec';
import Utils from './utils';

export interface MouseDownSite {
    left: number,
    top: number
}

export default class HtmlToCanvas{
    // 移动canvasdom
    private static movingCanvas: HTMLDivElement
    // 记录移动位置数据
    private static mouseDownSite: MouseDownSite

    /**
     * 创建divDom开始移动
     * @param dom
     * @param e
     */
    @ToolsDec.functionDoingOne
    static async createCanvas(dom: HTMLElement, e: MouseEvent): Promise<void> {
        this.cleanMovingDom();
        const Pos = Utils.getDocumentPos(dom);
        this.mouseDownSite = {
            left: e.clientX - Pos.left,
            top: e.clientY - Pos.top,
        };
        try {
            document.body.classList.add('dropping');
            const canvas: Node = dom.cloneNode(true);
            this.movingCanvas = DomCreate.createCanvasOutDom(e, {
                left: Pos.left,
                top: Pos.top
            }, {
                width: dom.clientWidth,
                height: dom.clientHeight
            });
            this.movingCanvas.append(canvas);
            document.body.append(this.movingCanvas);
        } catch (error) {
            console.log('如果单元测试输出请不要在意，node环境中没有全局Node变量,否则就是生成html2canvas出问题');
            this.movingCanvas = DomCreate.createCanvasOutDom(e, {
                left: dom.offsetLeft,
                top: dom.offsetTop
            }, {
                width: dom.clientWidth,
                height: dom.clientHeight
            });
            document.body.append(this.movingCanvas);
        }
    }

    /**
     * 移动状态
     * @param e
     */
    static moveCanvas(e: MouseEvent): void {
        if (!this.movingCanvas) {return;}
        this.movingCanvas.style.left = `${e.clientX - this.mouseDownSite.left}px`;
        this.movingCanvas.style.top = `${e.clientY - this.mouseDownSite.top}px`;
    }

    /**
     * 停止canvas拖拽
     * @param e
     */
    static stopCanvas(e: MouseEvent): void {
        this.cleanMovingDom();
    }

    /**
     * 自发性判断移除移动中的dom
     */
    private static cleanMovingDom() {
        if (this.movingCanvas) {
            document.body.classList.remove('dropping');
            document.body.removeChild(this.movingCanvas);
            this.movingCanvas = null;
        }
    }

    /**
     * 获取正在移动的canvas对象（单元测试会用）
     * @returns {HTMLDivElement}
     */
    static getMovingCanvas(): HTMLDivElement {
        return this.movingCanvas;
    }
}
